package com.hzdesk.media.matvector.koreabatch.client.my_paperless.fragment.Fragment_persenter;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.hzdesk.media.matvector.koreabatch.client.my_paperless.R;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.config.AppConfig;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.config.RBConfig;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.fragment.fragment_contract.IPersonalCenterContract;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.fragment.fragment_modle.PersonalCenterModle;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.logic.view.CaptureActivity;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.utils.JsonUitl;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.utils.SharedPreferencesUtils;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/8/9.
 */

public class PersonalCenterPersenter implements IPersonalCenterContract.IPersonalCenterPersenter {
    private String TAG = PersonalCenterPersenter.class.getSimpleName();
    private IPersonalCenterContract.IPersonalCenterView iPersonalCenterView;
    private Context mContext;
    private Activity mActivity;
    private IPersonalCenterContract.IPersonalCenterModle mIPersonalCenterModle;
    private Handler handler = new Handler();
    private TextView tv_cancel;
    private TextView tv_determine;
    private PopupWindow popup;

    public PersonalCenterPersenter(IPersonalCenterContract.IPersonalCenterView iPersonalCenterView) {
        this.iPersonalCenterView = iPersonalCenterView;
        mIPersonalCenterModle = new PersonalCenterModle();
    }

    @Override
    public void initView(Context context, Activity activity) {
        mContext = context;
        mActivity = activity;
        if (SharedPreferencesUtils.downloadOnlyInWireless(mContext)) {
            iPersonalCenterView.switchOpen();
        } else {
            iPersonalCenterView.switchClose();
        }
    }

    @Override
    public void onClickedImageViewScanner() {
        requestPermissions();

    }

    @Override
    public void onClickedImageViewMessage() {
        iPersonalCenterView.toMessagePager();
    }

    @Override
    public void onClickedImageVieHead() {
        iPersonalCenterView.toPersonalInformationPager();
    }

    @Override
    public void onClickedReMyGroup() {
        iPersonalCenterView.toMyOrganizationPager();
    }

    @Override
    public void onClickedImageViewSwitch() {
        if (SharedPreferencesUtils.downloadOnlyInWireless(mContext)) {
            SharedPreferencesUtils.getInstance(mContext).putDate(AppConfig.DOWNLOAD_ONLY_IN_WIRELESS, false);
            iPersonalCenterView.switchClose();
        } else {
            SharedPreferencesUtils.getInstance(mContext).putDate(AppConfig.DOWNLOAD_ONLY_IN_WIRELESS, true);
            iPersonalCenterView.switchOpen();
        }


    }
    // 技术支持
    @Override
    public void onClickedReTechnicalSupport() {
        iPersonalCenterView.toTechnicalSupportPager();
    }

    @Override
    public void onClickedReExit(final Context context) {
        OkHttpUtils
                .post()
                .url(RBConfig.HOST_IP+RBConfig.USER_LOGINOUT)
                .addHeader("sessionId",mIPersonalCenterModle.getToken(context))
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetWorkResponse = JsonUitl.NetWorkResponse(response);
                        if(NetWorkResponse != null){
                            JSONObject object = JsonUitl.NetworkResponseDateDeal(NetWorkResponse);
                            if(object != null){
                                int codo = JsonUitl.getParsinCode(object);
                                if(codo == 100){
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            iPersonalCenterView.showToastInfo("退出成功");
                                            // todo 退出登录
                                            iPersonalCenterView.toLoginPager();
                                            // todo 修改desk_media_is_login 记录是否登录成功
                                            mIPersonalCenterModle.saveIslogin(context);

                                        }
                                    });
                                }else{
                                    // todo 切换到主线程
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            iPersonalCenterView.showToastInfo("退出失败");
                                        }
                                    });
                                }
                            }
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                iPersonalCenterView.showToastInfo("退出失败");
                            }
                        });
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        String s = data.getStringExtra("result");
        Log.e(TAG, "onActivityResult:" + s);
        if (!s.equals("")){
            Toast.makeText(mContext, s, Toast.LENGTH_SHORT).show();

        }else {
            Toast.makeText(mContext, "扫描失败", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onClickedChangePassword() {
        iPersonalCenterView.toChangePasswordPager();
    }

    @Override
    public void showLogoutDialog(final Context context) {
        // todo 弹出退出提示框
        View view = View.inflate(mContext, R.layout.logout_info_layout, null);
        tv_cancel = view.findViewById(R.id.logout_info_layout_tv_cancel);
        tv_determine = view.findViewById(R.id.logout_info_layout_tv_determine);
        popup = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        popup.setAnimationStyle(R.style.ActionSheetDialogAnimation);
        popup.setOutsideTouchable(true);
        popup.setOutsideTouchable(true);
        popup.setTouchable(true);
        popup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popup.setFocusable(true);
        popup.setTouchable(true);
        popup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popup.showAtLocation(view, Gravity.CENTER,0,0);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popup.dismiss();
            }
        });
        tv_determine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onClickedReExit(context);
                popup.dismiss();
            }
        });
    }

    private void requestPermissions() {
        new RxPermissions(mActivity)
                .requestEach(Manifest.permission.CAMERA)
                .subscribe(new io.reactivex.functions.Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        // 用户已经同意该权限
                        if (permission.granted) {
                            Intent intent = new Intent();
                            intent.setClass(mContext, CaptureActivity.class);
                            iPersonalCenterView.toStartActivityForResult(intent, 1);
                        }
                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                        else if (permission.shouldShowRequestPermissionRationale) {
                        }
                        // 用户拒绝了该权限，并且选中『不再询问』
                        else {
                        }
                    }
                });
    }

}
